var network = true;

mui.ready(chkNetWork);

function chkNetWork() {
	//判断网络连通
	if (mui.os.plus) {
		mui.plusReady(function() {
			if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
				network = false;
			}
		});
	}
};
/*
 * 将form中的值转换为键值对 形如：{name:'aaa',password:'tttt'}
 * 注意将同名的放在一个数组里
 **/
function getFormJson(frmId) {
	var o = {};
	var a = $("#" + frmId).serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push($.trim(this.value) || '');
		} else {
			o[this.name] = $.trim(this.value) || '';
		}
	});
	return o;
}

/**
 * 打开窗口
 */
function openPage(_id, _url, _params) {
	mui.openWindow({
		id: _id,
		url: _url,
		extras: _params,
		preload: true,
		show: {
			aniShow: 'pop-in'
		},
		styles: {
			popGesture: 'hide'
		},
		waiting: {
			autoShow: false
		}
	});
}

/*
 * 接收地址栏参数  key:参数名称
 **/
function getQuery(key) {
	var search = location.search.slice(1); //得到get方式提交的查询字符串
	var arr = search.split("&");
	for (var i = 0; i < arr.length; i++) {
		var ar = arr[i].split("=");
		if (ar[0] == key) {
			if (ar[1] == 'undefined') {
				return "";
			} else {
				return ar[1];
			}
		}
	}
	return "";
}
/*
 * 验证是否为空
 */
function isEmpty(str) {
	var isOK = false;
	if (str == undefined || str == "" || str == "null") {
		isOK = true;
	}
	return isOK;
}

/**
 * 判断是否需要登录
 */
function isLogin(rsp){
	if (!isEmpty(rsp)) {
		if (!rsp.status && rsp.msg.indexOf("token") >= 0) {
            localStorage.removeItem("token");//失效移除
			window.location.href = contextName + "/login.html";
		}
	}
}
/**
 * get 请求
 * params: a=1&b=2
 */
function get(url, params, callBack) {
	if (!network) {
		mui.toast("当前网络不给力，请稍后再试");
		return;
	}
	mui.ajax(url, {
		data: params,
		dataType: 'json',
		type: 'get',
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Content-Type': 'application/json',
			'token': localStorage.getItem("token")
		},
		success: function(rsp) {
			isLogin(rsp);
			if(callBack != null)
				callBack(rsp);
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(type);
		}
	});
}

/**
 * post 请求
 */
function post(url, params, callBack) {
	if (!network) {
		mui.toast("当前网络不给力，请稍后再试");
		return;
	}
	mui.ajax(url, {
		data: params,
		dataType: 'json',
		type: 'post',
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Content-Type': 'application/json',
			'token': localStorage.getItem("token")
		},
		success: function(rsp) {
			isLogin(rsp);
			if(callBack != null)
				callBack(rsp);
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(type);
		}
	});
}
